const app = getApp()
var api = require('../../../utils/api.js')
var util = require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    total_price: "0",
    buy_type: "1",
    buyType: "1",
    invoiceNeed: "0",
    invoiceType: "2",
    invoiceTextType: "1",
    addressCol: true,
    Email:'',
    remarkCol: true, //发票弹窗
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var oid = options.oid;
    this.setData({
      oid: oid
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
    var that = this;
    //发票授权开关
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.invoiceTitle']) {
          that.setData({
            invoiceAuthorize: '1'
          })
        } else {
          that.setData({
            invoiceAuthorize: '3'
          })
        }
      }
    })


    this.addressList();
  },

  //获取授权信息
  getSetting: function () {
    var that = this;
    wx.authorize({
      scope: 'scope.invoiceTitle',
      success(res) {
        that.obtainInvoice();
      },
      fail(){
        that.setData({
          invoiceAuthorize: '2'
        })
      }
    })
  },

  // 发票类型选择
  invoiceTypeCol: function (e) {
    this.setData({
      invoiceType: e.currentTarget.dataset.invoicetype
    })
  },
  // 发票抬头类型选择
  invoiceTextTypeCol: function (e) {
    this.setData({
      invoiceTextType: e.currentTarget.dataset.invoicetexttype
    })
  },
  // 企业名称输入
  EnameCol: function (e) {
    this.setData({
      Ename: e.detail.value
    })
  },
  // 纳税人识别号
  EnumberCol: function (e) {
    this.setData({
      Enumber: e.detail.value
    })
  },
  // 接收电子发票的邮箱
  EmailCol: function (e) {
    this.setData({
      Email: e.detail.value
    })
  },
  // 企业注册地址
  EaddressCol: function (e) {
    this.setData({
      Eaddress: e.detail.value
    })
  },
  // 企业电话号码
  phoneNumberCol: function (e) {
    this.setData({
      phoneNumber: e.detail.value
    })
  },
  // 企业开户银行
  bankNameCol: function (e) {
    this.setData({
      bankName: e.detail.value
    })
  },
  // 企业银行账号
  bankNumberCol: function (e) {
    this.setData({
      bankNumber: e.detail.value
    })
  },
  // 个人抬头名称
  nameCol: function (e) {
    this.setData({
      name: e.detail.value
    })
  },

  //地址列表
  addressList: function () {
    var params = new Object()
    var that = this;
    api.POST({
      params: params,
      url: app.globalData.base_url + 'address/list',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          var addressLength = res.data.data.address_list.length;
          var addressList = res.data.data.address_list;
          for (var i = 0; i < addressList.length; i++) {
            if (addressList[i].is_default == 1) {
              var addressId = addressList[i].aid
            }
          }

          that.setData({
            addressId: addressId,
            address: addressList,
            addressLength: addressLength
          })
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },
  //添加新地址
  addAddress: function () {
    wx.navigateTo({
      url: '/index/pages/addAddress/addAddress'
    })
  },
  //显示地址弹窗
  selAddress: function () {
    this.setData({
      addressCol: false
    })
  },
  //修改地址
  editorAddress: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/index/pages/addAddress/addAddress?aid=' + id
    })
  },
  //删除地址
  deleteAddress: function (e) {
    var id = e.currentTarget.dataset.id;
    var that = this;

    wx.showModal({
      title: '提示',
      content: '确认删除该地址?',
      confirmColor: "#e51927",
      success: function (res) {
        if (res.confirm) {
          api.POST({
            params: { aid: id },
            url: app.globalData.base_url + 'address/del',
            success: function (res) {
              if (util.isEmpty(res.data.code)) {
                util.showStatus("删除成功")
                that.addressList();
              }
            },
            fail: function (fail) {
              util.showError("登录失败，请检查网络");

            }
          })
        } else if (res.cancel) {
          // console.log('用户点击取消')
        }
      }
    })
  },

  //选择地址
  radioChange: function (e) {
    var id = e.detail.value
    var that = this;
    var list = that.data.address;
    for (var i = 0; i < list.length; i++) {
      // console.log(list[i].aid);
      if (list[i].aid == id) {
        var params = {
          aid: id,
          username: list[i].username,
          mobile: list[i].mobile,
          province: list[i].province.name,
          town: list[i].town.name,
          city: list[i].city.name,
          address: list[i].address,
          is_default: 1,
          street: list[i].street.name
        }
        // console.log(params);
        api.POST({
          params: params,
          url: app.globalData.base_url + 'address/modify',
          success: function (res) {
            if (util.isEmpty(res.data.code)) {
              // that.addressList();
              that.setData({
                "controlDome": true
              })
            }
          },
          fail: function (fail) {
            util.showError("登录失败，请检查网络");

          }
        })

      }
    }
  },

  //隐藏地址
  hiddenAddress: function () {
    var that = this;
    that.setData({
      addressCol: true
    })
  },
  //确认收货地址
  confirmAddress: function () {
    this.setData({
      addressCol: true
    })
    this.addressList();
  },
  // 获取微信发票信息
  obtainInvoice: function () {
    var that = this;
    wx.chooseInvoiceTitle({
      success(res) {
        console.log(res);
        var types = res.type,
          title = res.title,
          telephone = res.telephone,
          taxNumber = res.taxNumber,
          companyAddress = res.companyAddress,
          bankName = res.bankName,
          bankAccount = res.bankAccount

        if (that.data.invoiceTextType == 2) {
          if (types == 0) {
            that.setData({
              Ename: title,
              Enumber: taxNumber,
              Eaddress: companyAddress,
              bankName: bankName,
              bankNumber: bankAccount
            })
          } else {
            util.showError("抬头类型错误");
          }

        }
      },
      fail(){
        that.setData({
          invoiceAuthorize: '2'
        })
      }
    })
  },

  // 确认发票信息
  invoiceConfirm: function () {
    var invoiceType = this.data.invoiceType;
    if (invoiceType == 1) {
      this.setData({
        invoiceTypeCol: true
      })
    } else {
      this.setData({
        invoiceTypeCol: false
      })
    }
    this.invoiceTextTypeDecide();



  },
  // 个人或者企业发票判断
  invoiceTextTypeDecide: function () {
    if (this.data.invoiceTextType == 1) {  //个人发票
      this.invoiceTypeDecide();
    } else if (this.data.invoiceTextType = 2) {  //企业发票
      if (util.isEmpty(this.data.Ename)) {
        util.showStatus("请输入企业名称");
        return false
      }

      if (util.isEmpty(this.data.Enumber)) {
        util.showStatus("请输入纳税人识别号");
        return false
      }


      if (!util.isEmpty(this.data.phoneNumber)) {
        if (!util.validateMobile(this.data.phoneNumber)) {
          util.showStatus("企业电话号不正确");
          return false
        }
      }

      if (!util.isEmpty(this.data.bankNumber)) {
        if (util.isEmpty(this.data.bankName)) {
          util.showStatus("请输入开户行");
          return false
        }
        if (!util.checkBankNo(this.data.bankNumber)) {
          util.showStatus("银行账号不正确");
          return false
        }
      }

      this.invoiceTypeDecide();
    }
  },
  //发票类型判断
  invoiceTypeDecide: function () {
    if (this.data.invoiceType == 1) {  //普通发票
      this.setData({
        invoice: true
      })
    } else if (this.data.invoiceType = 2) {  //电子发票
      var email = this.data.Email;
      email = email.replace(/\s*/g, "");  //去除空格
      if (util.validateEmail(email)) {
        this.setData({
          invoice: true
        })
      } else {
        util.showStatus("邮箱地址错误");
        return false
      }
    }
    
    this.setData({
       remarkCol:false
    })
   //  this.invoiceSubmit();
  },
   remarkCancel:function(){
      this.setData({
         remarkCol: true
      })
   },
   remarkSubmit:function(){
      this.setData({
         remarkCol: true
      })
      this.invoiceSubmit();
   },


  //提交发票信息
  invoiceSubmit: function () {
    var params = new Object()
    var that = this;
    params.oid=this.data.oid;
    if (this.data.invoiceTextType == 1) {  //个人发票

      params.invoice = "个人";
      if (this.data.invoiceType == 2) {  //电子发票
        params.invoice_email = this.data.Email;
        params.invoice_type = 2
      } else {
        params.invoice_type = 1;
        var address = this.data.address
        for (var i = 0; i < address.length; i++) {
          if (address[i].is_default == 1) {
            params.aid = address[i].aid
          }
        }

        if (params.aid == undefined || params.aid == '') {
          util.showError("请选择收货地址");
          return false;
        }
      }

    } else if (this.data.invoiceTextType == 2) {  //企业发票
      params.invoice = this.data.Ename;
      params.invoice_number = this.data.Enumber;
      if (this.data.invoiceType == 2) {  //电子发票
        params.invoice_email = this.data.Email;
        params.invoice_type = 2
      } else {
        params.invoice_type = 1;
        var address = this.data.address
        for (var i = 0; i < address.length; i++) {
          if (address[i].is_default == 1) {
            params.aid = address[i].aid
          }
        }

        if (params.aid == undefined || params.aid == '') {
          util.showError("请选择收货地址");
          return false;
        }
      }

      if (!util.isEmpty(this.data.Eaddress)) {
        params.invoice_e_r_address = this.data.Eaddress
      }

      if (!util.isEmpty(this.data.phoneNumber)) {
        params.invoice_e_tel = this.data.phoneNumber
      }

      if (!util.isEmpty(this.data.bankNumber)) {
        params.invoice_e_bank_name = this.data.bankName
        params.invoice_e_bank_number = this.data.bankNumber
      }
    }
    // console.log(params);
    api.POST({
      params: params,
      url: app.globalData.base_url + 'order/addInvoice',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          // util.showError("发票信息已上传");
       

          wx.showModal({
            title: '提示',
            showCancel:false,
            content: '发票信息已上传，点击返回',
            success: function (res) {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })


        } else {
          util.showStatus(res.data.message)
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },
})